package com.platform.car.app;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.platform.car.model.Parkingpay;
import com.platform.car.service.ParkingpayService;
import com.platform.common.tld.AliPayUtils;
import com.platform.pay.model.Alipay;
import com.platform.pay.service.AlipayService;
import com.platform.upms.model.json.Tip;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
* 支付宝支付管理 客户端 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/app/alipay")
public class AppAlipayController {

    /**
     * 支付宝下订单
     * @param outtradeno 订单号 parkingpay的Id
     * @param type  支付的类型 0：支付宝支付 1：微信支付
     * @return 支付宝订单
     */
    @RequestMapping(value="/genOrder")
    @ResponseBody
    public Tip genOrder(Integer outtradeno,String type){
        Alipay alipay=null;
        Parkingpay parkingpay = parkingpayService.selectById(outtradeno);//根据订单号查询
        if(parkingpay == null){
            return null;
        }
        if(parkingpay.getParkingId() !=null){
            if(type !=null && "".equals(type)){
                if("0".equals(type)){//支付宝支付
                     alipay=alipayService.selectByReceiveId(parkingpay.getParkingId());//查询支付宝的详情信息
                }
                if("1".equals(type)){//微信支付
//                    Wechat wechat=wechatService.listValid(estateId);
                    return new Tip(2,"敬请期待");
                }
            }else{
                return new Tip(2,"请选择支付的方式");
            }
        }

        if(alipay !=null){
            //实例化客户端
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                   alipay.getAppId(), alipay.getSignPrivateKey(), "json",alipay.getInputCharset(),alipay.getAlipayPublicKey(), "RSA2");
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody("白天总时长："+parkingpay.getDaylight()+"\n夜间总时长："+parkingpay.getNight()+"\n总费用："+ parkingpay.getPayfee());
            model.setSubject("停车费用支付");
            model.setOutTradeNo(outtradeno.toString());
            model.setTimeoutExpress("30m");
            model.setTotalAmount(String.valueOf(parkingpay.getPayfee()));
            model.setProductCode("QUICK_MSECURITY_PAY");
            request.setBizModel(model);
            request.setNotifyUrl("https://zhsq.lianxinyi.com.cn:8444/app/alipay/notifyTradeNo");
            try {
                //这里和普通的接口调用不同，使用的是sdkExecute
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                System.out.println("准备支付订单："+response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
                return new Tip("成功生成订单，请支付！",response.getBody());
            } catch (AlipayApiException e) {
                e.printStackTrace();
                return new Tip(1,"订单生成失败！");
            }
        }else{
            return  new Tip(3,"暂无支付宝收款信息");
        }
    }

    /**
     * 支付宝回调的接口
     * @param request
     * @return
     */
    @RequestMapping(value="/notifyTradeNo")
    @ResponseBody
    public Boolean notifyTradeNo(HttpServletRequest request){
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]  : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
            System.out.println("name：" + name +"    value：" + valueStr);
        }

        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean flag = false;
        try {
            flag = AlipaySignature.rsaCheckV1(params, AliPayUtils.ALIPAY_PUBLIC_KEY, AliPayUtils.CHARSET, "RSA2");
            System.out.println("验证结果：" + flag);
            if(flag){
                System.out.println("支付成功！");
                String outTradeNo = params.get("out_trade_no");
                Parkingpay parkingpay = parkingpayService.get(outTradeNo);
                if(parkingpay != null){
                    parkingpay.setStatus("1");
                    parkingpayService.update(parkingpay);
                }
            }else{
                System.out.println("支付失败！");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("修改支付状态失败！");
        }
        return flag;
    }



    //---------------------------- property -------------------------------

    @Resource
    private ParkingpayService parkingpayService;

    @Resource
    private AlipayService alipayService;

}
